/**
 * Created by Administrator on 2015/5/14.
 */

//可选菜单
var allMeals = null;

//生效的订单
var effectOrders = null;

//总价格
var priceCount = 0;

var url = location.search;

var payment = false;
if (url.indexOf("payment") > -1) {
    payment = true;
}

$(function () {
    var date = getDate();
    $('#date').html(date);
    queryMeals();
    query();
    readCookie();
});


var order = function () {
    var date = $('#date').html();
    var name = $("#userSelect").find("option:selected").text();
    var uid = $("#userSelect").val();
    var meal = $('#meal').val();
    var price = $('#price').val();
    if (!uid || uid == "") {
        alert("你是谁？");
        return;
    }
    if (!meal || meal == "") {
        alert("你点啥子？");
        return;
    }
    if (!price || price == "") {
        alert("请输入价格！所有套餐9折！");
        return;
    }
    if (isNaN(price)) {
        alert("请输入合理的价格");
        return;
    }
    price = price * 0.9;
    addCookie(name);
    $("#orderbtn").attr('disabled', true);
    var url = "/orders/order?date=" + date + "&name=" + name + "&meal=" + meal + "&uid=" + uid + "&price=" + price;
    var encodeUrl = encodeURI(url);
    //console.log(encodeUrl);
    $.ajax({
        type: "get",
        //url: "/orders/order?date=" + date + "&name=" + name + "&meal=" + meal,
        url: encodeUrl,
        cache: false,
        success: function (result) {
            if (result.status == "ok") {
                alert("订餐成功");

            } else {
                alert("订餐失败");
            }
            query();
            form.submit();
        }
    });
}

var addCookie = function (name) {
    var expireDate = new Date();
    expireDate.setDate(expireDate.getDate() + 365);
    var str = "name=" + name + ";expires=" + expireDate.toGMTString();
    //alert(str);
    //document.cookie = str;
}

var readCookie = function () {
    var temp = document.cookie.split("=");
    var name = temp[1];
    $('#name').val(name)
}

var query = function () {
    var date = $('#date').html();
    $.ajax({
        type: "get",
        url: "/orders/queryOrders?date=" + date,
        cache: false,
        success: function (orders) {
            effectOrders = orders;
            $('#number').html(":" + orders.length);
            showOrders(orders);
        }
    });
}
var showOrders = function (orders) {
    priceCount = 0;
    var table = $('<table></table>');
    var head = $('<tr><th>名称</th><th>点餐</th><th>价格</th><th>时间</th><th>操作</th></tr>');
    head.appendTo(table);
    for (var i = 0; i < orders.length; i++) {
        var tr = $('<tr></tr>');
        var order = orders[i];
        var name = $('<td>' + order.name + '</td>');
        var meal = $('<td>' + order.meal + '</td>');
        var time = $('<td>' + order.time + '</td>');
        var price = $('<td>' + order.price + '</td>');

        if (order.price) {
            var floatPrice = parseFloat(order.price);
            priceCount += floatPrice;
            //console.log(priceCount, floatPrice , order.price);
        }
        var actionStr = '<td>';
        if (payment) {
            actionStr += '<input type="button" value="删除" onclick="deleteOrder(\'' + order._id + '\')">';
            if (order.payment == '1') {
                actionStr += '已付款';
            } else {
                actionStr += '<input type="button" value="付款" onclick="payOrder(\'' + order._id + '\')">';
            }

        }
        actionStr += '</td>';
        var action = $(actionStr);
        name.appendTo(tr);
        meal.appendTo(tr);
        price.appendTo(tr);
        time.appendTo(tr);
        action.appendTo(tr);
        tr.appendTo(table);
    }
    $('#number').html("" + orders.length);
    $('#priceCount').html(priceCount.toFixed(1));
    $('#orders').html("");
    table.appendTo($('#orders'));
}


var getDate = function () {
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var dateStr = year + "-" + month + "-" + day;
    return dateStr;
}


var queryMeals = function () {
    $.ajax({
        type: "get",
        url: "/orders/queryMeals",
        cache: false,
        success: function (meals) {
            allMeals = meals;
            showMeals(meals);
        }
    });
}


var showMeals = function (meals) {
    var row = $('<div class="line"></div>')
    for (var i = 0; i < meals.length; i++) {
        if (i % 4 == 0 && i > 0) {
            row.appendTo($('#meals'));
            row = $('<div class="line"></div>');
        }

        var meal = meals[i];
        var html = $('<div id="' + meal._id + '" onclick="choose(this)" value="' + meal.name + '"><label>￥' + meal.price + '</label>' + meal.name + '</div>');
        html.appendTo(row);
        if (i == meals.length - 1) {
            row.appendTo($('#meals'));
            row = $('<div class="line"></div>');
        }
    }
}


var randomChoose = function () {
    var choose = Math.floor(Math.random() * allMeals.length);
    var meal = allMeals[choose];
    $('#meal').val(meal.name);
}


var choose = function (element) {
    var name = $(element).attr("value");
    $('#meal').val(name);
}


var payOrder = function (orderId) {
    var date = $('#date').html();
    $.ajax({
        type: "get",
        url: "/orders/payOrder?date=" + date + "&orderId=" + orderId,
        cache: false,
        success: function (result) {
            if (result.status == "ok") {
                alert("付款成功！");
            } else {
                alert("付款失败");
            }
            query();
        }
    });
}

var deleteOrder = function (orderId) {
    if (!window.confirm("是否要删除该订单？")) {
        return;
    }
    var date = $('#date').html();
    $.ajax({
        type: "get",
        url: "/orders/deleteOrder?date=" + date + "&orderId=" + orderId,
        cache: false,
        success: function (result) {
            if (result.status == "ok") {
                alert("订餐删除成功");
            } else {
                alert("订餐删除失败");
            }
            query();
        }
    });
}


var statistics = function () {
    if (!effectOrders || effectOrders.length == 0) {
        alert("此时，应该无人订餐！");
        return;
    }
    var result = {};
    for (var i = 0; i < effectOrders.length; i++) {
        var order = effectOrders[i];
        if (result[order.meal]) {
            result[order.meal] = result[order.meal] + 1;
        } else {
            result[order.meal] = 1;
        }
    }
    var str = "";
    for (var key in result) {
        str += key + " : " + result[key] + "\n";
    }
    alert(str);
}


var showUsers = function () {
    $.ajax({
        type: "get",
        url: "/users/list",
        cache: false,
        success: function (users) {
            for (var i = 0; i < users.length; i++) {
                var user = users[i];
                $("#userSelect").append("<option value='" + user.uid + "'>" + user.name + "</option>");
            }
        }
    });
}

showUsers();